//go:build ignore
// +build ignore

package main

import (
	"flag"
	v1 "helloworld/api/server/v1"
	"log"
	"net/url"
	"os"
	"os/signal"
	"time"

	"gitee.com/carlzyhuang/framework/rpc/websocket/protocol"
	"github.com/gorilla/websocket"
	"google.golang.org/protobuf/proto"
)

var addr = flag.String("addr", "localhost:7000", "http service address")

const (
	HelloworldMessageID = v1.CMD_WsGreeter_SayHello
)

func main() {
	flag.Parse()
	log.SetFlags(0)

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	u := url.URL{Scheme: "ws", Host: *addr, Path: "/ws"}
	log.Printf("connecting to %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}

			msg := &protocol.ResponsePacket{}
			if err := proto.Unmarshal(message, msg); err != nil {
				log.Println("unmarshal:", err)
				return
			}

			payload := &v1.HelloReply{}
			if msg.Header.MessageId == HelloworldMessageID {
				if err := proto.Unmarshal(msg.Payload, payload); err != nil {
					log.Println("unmarshal biz payload:", err)
					return
				}

			}

			log.Printf("收到消息 <- recv: %s", msg.Header.String()+", payload: "+payload.String())

		}
	}()

	ticker := time.NewTicker(time.Second * 3)
	defer ticker.Stop()

	for {
		select {
		case <-done:
			return
		case <-ticker.C:

			bizPayload := &v1.HelloRequest{Name: "WebSocket Client" + time.Now().Format(time.DateTime)}
			payloadData, err := proto.Marshal(bizPayload)
			if err != nil {
				log.Println("marshal biz payload:", err)
				return
			}

			reqMsg := &protocol.RequestPacket{
				Header: &protocol.Header{
					MessageId: HelloworldMessageID,
					Timestamp: uint64(time.Now().Unix()),
					Version:   0,
				},
				Payload: payloadData,
			}

			data, err := proto.Marshal(reqMsg)
			if err != nil {
				log.Println("marshal:", err)
				return
			}

			err = c.WriteMessage(websocket.BinaryMessage, data)
			log.Println("定时发送消息-> send:", reqMsg.Header.String()+", payload: "+bizPayload.String())
			if err != nil {
				log.Println("write:", err)
				return
			}
		case <-interrupt:
			log.Println("interrupt")

			// Cleanly close the connection by sending a close message and then
			// waiting (with timeout) for the server to close the connection.
			err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			if err != nil {
				log.Println("write close:", err)
				return
			}
			select {
			case <-done:
			case <-time.After(time.Second):
			}
			return
		}
	}
}
